package com.lw.leetcode.bit.b;

/**
 * Created with IntelliJ IDEA.
 * <p>
 * bit
 * 991. 坏了的计算器
 *
 * @author liw
 * @version 1.0
 * @date 2021/8/6 16:30
 */
public class BrokenCalc {

    public static void main(String[] args) throws InterruptedException {

        BrokenCalc test = new BrokenCalc();

        // 68 71    34
//        int a = 68;
//        int b = 71;

        // 5 3    2
//        int a = 5;
//        int b = 3;

        // 2 3    2
//        int a = 2;
//        int b = 3;

        // 5
//        int a = 14;
//        int b = 100;

        // 363 811   163
//        int a = 363;
//        int b = 811;

        // 63 95    17
        int a = 63;
        int b = 95;

        // 368 1003   120
//        int a = 368;
//        int b = 1003;


        int i = test.brokenCalc(a, b);
        System.out.println(i);

    }

    public int brokenCalc(int startValue, int target) {
        if (startValue >= target) {
            return startValue - target;
        }
        int f = 0;
        if ((target & 1) == 1) {
            target++;
            f = 1;
        }
        long item = startValue;
        int n = 0;
        while (item < target) {
            item = item << 1;
            n++;
        }
        f += n;
        item -= target;
        long count = item + f;
        int i = 0;
        int c = 0;
        while (item > 0) {
            if (n < 0) {
                return (int) (((item) << 1) + c + f);
            }
            if ((item & 1) == 1) {
                count = count - (2 << (i - 1)) + 1;
                c++;
            }
            i++;
            n--;
            item = (item >> 1);
        }
        return (int) count;
    }
}
